package com.milk.nettylearn.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

import static com.milk.nettylearn.nio.ByteBufferUtil.debugAll;

@Slf4j
public class SelectorTypeServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false);
        ssc.register(selector, 0, null).interestOps(SelectionKey.OP_ACCEPT);


        while (true) {
            // 等待消息
            selector.select();

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                log.debug("key :{} ", key);
                iterator.remove();
                if (key.isAcceptable()) {
                    // 连接事件
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    SocketChannel accept = channel.accept();
                    log.debug("connecting :{}", accept);
                    accept.configureBlocking(false);
                    accept.register(selector, 0, ByteBuffer.allocate(16)).interestOps(SelectionKey.OP_READ);
                }
                if (key.isReadable()) {
                    try {
                        // 读事件
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        int read = channel.read(buffer);
                        if (read != -1) {
//                            buffer.flip();
//                            log.debug("read :{}", channel);

                            split(buffer);
                            if (buffer.position() == buffer.limit()) {
                                // 未读取到分隔符,进行扩容
                                ByteBuffer newBuffer = ByteBuffer.allocate(buffer.capacity() * 2);
                                buffer.flip();
                                newBuffer.put(buffer);
                                key.attach(newBuffer);
                            }

                        } else {
                            // 断开连接了
                            key.cancel();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        log.debug("断开 :[]", e);
                        key.cancel();
                    }
                }
            }
        }
    }


    private static void split(ByteBuffer source) {
        source.flip();
        for (int i = 0; i < source.limit(); i++) {
            if (source.get(i) == '\n') {
                int length = i + 1 - source.position();
                ByteBuffer buffer = ByteBuffer.allocate(length);
                for (int j = 0; j < length; j++) {
                    buffer.put(source.get());
                }
                debugAll(buffer);
            }
        }
        source.compact();
    }
}
